import { getProfileAPI, loginAPT } from "@/apis/user";
import { setToken as _setToken, getToken, removeToken } from "@/utils";
import { createSlice } from "@reduxjs/toolkit";

const userStore = createSlice({
  name: 'user',
  initialState: {
    token: getToken() || '',
    userInfo: {}
  },
  // 同步方法
  reducers: {
    // 获取token
    setToken(state, action){
      state.token = action.payload
      // localStorage
      _setToken(action.payload)
    },
    // 获取用户信息
    setUserInfo(state, action){
      state.userInfo = action.payload
    },
    // 清除用户信息
    clearUserInfo(state){
      state.token = ''
      state.userInfo = {}
      removeToken()
    },
  }
})

// 解构出actionCreater
const { setToken, setUserInfo, clearUserInfo, } = userStore.actions

// 获取reducer
const useReducer = userStore.reducer 

// 异步方法
// 登录
const fetchLogin = (loginForm) => {
  return async (dispatch) => {
    // 发送异步请求
    const res = await loginAPT(loginForm)
    // 提交同步action进行token的存入
    dispatch(setToken(res.data.token))
  }
}
// 个人用户信息
const fetchUserInfo = () => {
  return async (dispatch) => {
    const res = await getProfileAPI()
    dispatch(setUserInfo(res.data))
  }
}

export { setToken, fetchLogin, fetchUserInfo, clearUserInfo }

export default useReducer


